#include "UtilityPCH.h"
#include "UT_BTDFSpecularTransmission.h"
#include "UT_MathHelper.h"

using namespace Utility;
//-------------------------------------------------------------------------
UT_BTDF_SpecularTransmission::UT_BTDF_SpecularTransmission(const UT_SpectrumUsed& rkT, float fEtai, float fEtat)
	: UT_BxDFBase(BxDFType(BSDF_TRANSMISSION | BSDF_SPECULAR))
	, m_kFresnel(fEtai,fEtat)
{
	m_kTransmitive = rkT;
	m_fEtai = fEtai;
	m_fEtat = fEtat;
}
//-------------------------------------------------------------------------
UT_SpectrumUsed UT_BTDF_SpecularTransmission::f(const UT_Vec3Float& wo, const UT_Vec3Float& wi) const
{
	return UT_SpectrumUsed(0);
}
//-------------------------------------------------------------------------
UT_SpectrumUsed UT_BTDF_SpecularTransmission::Sample_f(const UT_Vec3Float& wo, UT_Vec3Float* wi, float u1, float u2, float *pdf) const
{
	// Figure out which $\eta$ is incident and which is transmitted
	bool bEntering = ( UT_MathHelper::ComputeSphericalCosTheta(wo) > 0. );
	float ei = m_fEtai, et = m_fEtat;
	if (!bEntering)
		ut_swap(ei, et);

	// Compute transmitted ray direction
	float sini2 = UT_MathHelper::ComputeSphericalSinTheta2(wo);
	float eta	= ei / et;
	float sint2 = eta * eta * sini2;

	// Handle total internal reflection for transmission
	if (sint2 >= 1.)
		return 0.;
	
	float cost = UT_MathHelper::Sqrt(UT_MathHelper::Max(0.f, 1.f - sint2));
	if (bEntering) 
		cost = -cost;
	
	float sintOverSini = eta;
	*wi = UT_Vec3Float(sintOverSini * -wo.x, sintOverSini * -wo.y, cost);

	*pdf = 1.f;
	
	UT_SpectrumUsed F = m_kFresnel.Evaluate(UT_MathHelper::ComputeSphericalCosTheta(wo));
	
	return  (et*et)/(ei*ei) * (UT_SpectrumUsed(1.)-F) * m_kTransmitive / UT_MathHelper::ComputeSphericalAbsCosTheta(*wi);
}
//-------------------------------------------------------------------------
float UT_BTDF_SpecularTransmission::Pdf(const UT_Vec3Float& wi, const UT_Vec3Float& wo) const
{
	return 0;
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
